package cn.lxsir.uniapp.controller;

import cn.hutool.core.util.StrUtil;
import cn.lxsir.uniapp.common.Constants;
import cn.lxsir.uniapp.common.Result;
import cn.lxsir.uniapp.dto.UserDto;
import cn.lxsir.uniapp.entity.User;
import cn.lxsir.uniapp.mapper.UserMapper;
import cn.lxsir.uniapp.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;


/**
 * @ClassName UserController
 * @Description
 * @Author wangyang
 * @Date 2023/5/22 9:20
 * @Version 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Resource
    private UserMapper userMapper;

    @GetMapping
    public String test(){
        return "Hello";
    }
//    @PostMapping
//    @ApiOperation(value = "处理挑战赛的结果")
//    public R challengeResults(@RequestBody Map<String,Object> map){
//        Map<String, Object> map1 = challengeResultService.challengeResults(map);
//        return R.ok(map1);
//    }
    @PostMapping("/login")
    public Result login(@RequestBody UserDto userDto){
        String phone = userDto.getPhone();
        String password=userDto.getPassword();
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(password)) {
            return Result.error(Constants.CODE_400,"参数错误");
        }
        UserDto login = userService.login(userDto);
        return Result.success(login);
    }

    @PostMapping("/add")
    public Result add(@RequestBody User user){

        System.out.println(user);
        return Result.success(userMapper.updateById(user));
    }

    @PostMapping("/register")
    public Result register(@RequestBody UserDto userDTO) {
        String phone = userDTO.getPhone();
        String password = userDTO.getPassword();
//        String nickname = userDTO.getNickName();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if(StrUtil.isNotEmpty(phone)){

            List<User> list = this.userMapper.selectList(new LambdaQueryWrapper<User>()
                    .eq(User::getPhone, phone)
            );
            System.out.println(list);

//            LambdaQueryWrapper<User> wrapper = queryWrapper.eq(User::getPhone, phone);
//            System.out.println(wrapper);
            if(!list.isEmpty()){
                return Result.error(Constants.CODE_601, "用户已存在!");
            }
        }
        if (StrUtil.isBlank(phone) || StrUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        return Result.success(userService.register(userDTO));
    }
}
